package com.block.api.interceptor;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.encrypt.enums.EncryptTypeEnum;
import com.block.common.encrypt.factory.EncryptFactory;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.model.dto.EncryptKeyDTO;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.common.service.LogFactory;
import com.block.common.util.HttpReturnUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.ChannelBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;


/**
 * 联登渠道 过滤器
 */
public class InitUnionInterceptor implements HandlerInterceptor {

	private static final Logger log = LogFactory.getUnionLog();

	@Autowired
	IChannelCommonService channelCommonService;
	@Autowired
	NotifyExceptionService notifyExceptionService;
	@Autowired
	IApplicationInfoService applicationInfoService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		String uri = request.getRequestURI();
		String ip= ServletUtil.getClientIP(request);
		try {

			String paramContent = IoUtil.read(request.getInputStream(), Charset.defaultCharset());
			log.info("【联登请求】【请求地址】{}【请求参数】{}", uri, paramContent);

			JSONObject jsonObject = JSON.parseObject(paramContent);
			String channelCode = jsonObject.getString("channelCode");

			ChannelBaseInfo channelBaseInfo = channelCommonService.getBaseInfoByCode(channelCode);
			if (ObjectUtil.isEmpty(channelBaseInfo)){
				HttpReturnUtil.returnJson(response, ResultInfoVO.error("渠道信息为空"));
				return false;
			}
			if (ObjectUtil.equal(channelBaseInfo.getStatus(), Integer.valueOf(0))){
				HttpReturnUtil.returnJson(response, ResultInfoVO.error("渠道状态不可用"));
				return false;
			}

			// 请求验签
			String requestNo = jsonObject.getString("requestNo");
			String timestamp = jsonObject.getString("timestamp");

			EncryptKeyDTO encryptKeyDTO = new EncryptKeyDTO();
			encryptKeyDTO.setAppCode(channelBaseInfo.getChannelCode());
			encryptKeyDTO.setAppKey(channelBaseInfo.getAppKey());
			encryptKeyDTO.setAppSecret(channelBaseInfo.getAppSecret());
//			encryptKeyDTO.setPubKey(unionBaseInfo.getPubKey());
//			encryptKeyDTO.setPriKey(unionBaseInfo.getPriKey());

			//业务参数 解密
			JSONObject tranData = null;
			try {
				tranData = EncryptFactory.getService(EncryptTypeEnum.AES.getValue()).decryptTranData(encryptKeyDTO, jsonObject);
				log.info("【渠道联登】【解秘完数据】{}", JSON.toJSONString(tranData));
			}catch (Exception exception){
				exception.printStackTrace();
				HttpReturnUtil.returnJson(response, requestNo, ResultInfoVO.error("业务参数解密失败"));
				String content = StrUtil.format("【uri】{}【channelCode】{}【tranData】{}", uri, channelCode, tranData);
				notifyExceptionService.notifyNoticeInfo("UNION_REQUEST_TRANDATA", "联登业务数据解密异常", content, exception);
				return false;
			}

			if (ObjectUtil.isEmpty(tranData)){
				HttpReturnUtil.returnJson(response, requestNo, ResultInfoVO.error("业务参数解析失败"));
				return false;
			}

			ApplicationInfo applicationInfo = applicationInfoService.getAppInfoByAppCode(channelBaseInfo.getAppCode());

			request.setAttribute("tranData", tranData);
			request.setAttribute("requestNo", requestNo);
			request.setAttribute("channelBaseInfo", channelBaseInfo);
			request.setAttribute("applicationInfo", applicationInfo);
			request.setAttribute("uri", uri);
			request.setAttribute("ip", ip);

			return  true;
		} catch (Exception exception){
			log.error("拦截器处理异常json...",exception);
			HttpReturnUtil.returnJson(response, ResultInfoVO.error("处理异常：" + exception.getMessage()));
			String content = StrUtil.format("【uri】{}", uri);
			notifyExceptionService.notifyNoticeInfo("UNION_REQUEST", "联登请求异常", content, exception);
			return  false;
		}
	}

}
